package com.vitabuybuy.tv.ui.home.group

import android.os.Bundle
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout
import com.google.gson.reflect.TypeToken
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.mmkv
import com.library.common.net.loadingtype.LoadingType
import com.library.common.util.DensityUtil
import com.library.common.util.JsonUtil

import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityGroupBuyZoneBinding
import com.vitabuybuy.tv.dto.FirstCategoryDto
import com.vitabuybuy.tv.dto.TabEntity
import com.vitabuybuy.tv.ui.home.group.adapter.GroupBuyListZoneAdapter
import com.vitabuybuy.tv.ui.home.group.viewmodel.GroupBuyZoneViewModel
import com.vitabuybuy.tv.ui.shopcenter.CommodityClassificationActivity
import com.library.common.util.MMKVContancts
import kotlinx.android.synthetic.main.activity_group_buy_zone.*
import java.util.*

class GroupBuyZoneActivity : BaseActivity<GroupBuyZoneViewModel, ActivityGroupBuyZoneBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_group_buy_zone

    private val grouplistAdapter by lazy { GroupBuyListZoneAdapter() }
    private var categoryId = -1
    private var pageNumber = 1
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private lateinit var groupType: String

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        setTitle(getString(R.string.group_buy_area))
        groupType = getString(R.string.all)
        mTvRight.apply {
            visibility = View.VISIBLE
            text = getString(R.string.search)
            setTextColor(ContextCompat.getColor(mContext, R.color.white))
            setNormalSolid(ContextCompat.getColor(mContext, R.color.mainColor))
            setPressedSolid(ContextCompat.getColor(mContext, R.color.pressColor))
            setRadii(DensityUtil.dip2px(13f).toFloat())
            val params = layoutParams as RelativeLayout.LayoutParams
            params.rightMargin = DensityUtil.dip2px(12f)
            layoutParams = params
            setOnClickListener {
                SearchGroupBuyOrBiddingOrLiveActivity.openActivity(mContext,SearchGroupBuyOrBiddingOrLiveActivity.FROM_GROUP)
            }
        }

        mTabEntities.add(TabEntity(getString(R.string.all), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.normal_group_buy), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.limited_group_buy), 0, 0))
        tlBiddingClass.setTabData(mTabEntities)

        listview.apply {
            adapter = grouplistAdapter
            layoutManager = LinearLayoutManager(mContext)
        }
    }

    override fun observeData() {
        val categoryList = JsonUtil.fromJson(
            mmkv.decodeString(MMKVContancts.CATEGORY_LIST, ""),
            object : TypeToken<ArrayList<FirstCategoryDto>>() {}.type) as ArrayList<FirstCategoryDto>

        tlClassification.apply {
            removeAllTabs()
            addTab(
                tlClassification.newTab().setText(getString(R.string.recommend))
                    .setTag(categoryId)
            )
            for (str in categoryList) {
                addTab(tlClassification.newTab().setText(str.name).setTag(str.id))
            }
            viewModel.getGoodsList(
                categoryId,
                if (groupType == getString(R.string.all)) "" else groupType,
                null,
                pageNumber
            )
        }
        viewModel.goodslist.observe(this, Observer {
            if (pageNumber == 1) {
                grouplistAdapter.setNewData(it)
            } else {
                grouplistAdapter.addData(it)
            }
            if (grouplistAdapter.mData.isEmpty()) {
                viewModel.statusView.set(LoadingType.SHOW_EMPTY)
            }else{
                viewModel.statusView.set(LoadingType.SHOW_CONTENT)
            }
        })
    }


    override fun eventHandling() {
        tlBiddingClass.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                groupType = when (position) {
                    0 -> getString(R.string.all)
                    1 -> getString(R.string.normal_group_buy)
                    2 -> getString(R.string.limited_group_buy)
                    else -> getString(R.string.all)
                }
                pageNumber = 1
                viewModel.getGoodsList(
                    categoryId,
                    if (groupType == getString(R.string.all)) "" else groupType,
                    null,
                    pageNumber
                )
            }

            override fun onTabReselect(position: Int) {
            }
        })
        tlClassification.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                categoryId = tab?.tag as Int
                pageNumber = 1
                viewModel.getGoodsList(
                    categoryId,
                    if (groupType == getString(R.string.all)) "" else groupType,
                    null,
                    pageNumber
                )
            }

            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }
        })
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getGoodsList(
                    categoryId,
                    if (groupType == getString(R.string.all)) "" else groupType,
                    null,
                    pageNumber
                )
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber = 1
                viewModel.getGoodsList(
                    categoryId,
                    if (groupType == getString(R.string.all)) "" else groupType,
                    null,
                    pageNumber
                )
            }
        })
        ivClassification.setOnClickListener { CommodityClassificationActivity.openActivity(mContext,
            CommodityClassificationActivity.FROM_GROUP_BUY) }
        grouplistAdapter.setOnItemClickListener { binding, item, position ->
            GroupBuyDetailActivity.openActivity(mContext, item.id)
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                pageNumber = 1
                viewModel.getGoodsList(
                    categoryId,
                    if (groupType == getString(R.string.all)) "" else groupType,
                    null,
                    pageNumber
                )
            }
            1 -> {
                refresh.onLoad(msg.arg1)
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, GroupBuyZoneActivity::class.java)
        }
    }
}
